package com.test.recordaudio

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.provider.Settings
import androidx.activity.result.ActivityResultLauncher
import androidx.core.content.ContextCompat

const val CHANNEL_NAME = "FOREGROUND_SERVICE"

fun Context.requestPermission(permissionRequest: ActivityResultLauncher<Array<String>>): Boolean {
    val permissions = mutableListOf(
        android.Manifest.permission.RECORD_AUDIO
    )
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        permissions.add(android.Manifest.permission.FOREGROUND_SERVICE)
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
        permissions.add(android.Manifest.permission.FOREGROUND_SERVICE_MICROPHONE)
    }

    val denied = permissions.any {
        ContextCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED
    }

    if (denied) {
        permissionRequest.launch(Array(permissions.size) { permissions[it] })
        return false
    }

    val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    return if (notificationManager.areNotificationsEnabled()) {
        true
    } else {
        val intent = Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS).apply {
            putExtra(Settings.EXTRA_APP_PACKAGE, packageName)
        }
        startActivity(intent)
        false
    }
}

fun Context.initNotificationChannel() {
    val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    val channel = NotificationChannel(
        CHANNEL_NAME,
        "Foreground_service",
        NotificationManager.IMPORTANCE_LOW
    )
    notificationManager.createNotificationChannel(channel)
}